/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <Registrant.h>
#include <Message.h>

Registrant* newRegistrant(Handler* h, int what, void* userObj) {
    Registrant* registrant = (Registrant*) malloc(sizeof(Registrant));
    if (!registrant) {
        return NULL;
    }
    memset(registrant, 0, sizeof(Registrant));

    registrant->userObj = userObj;
    registrant->handler = h;
    registrant->what = what;
    return registrant;
}

void deleteRegistrant(Registrant* registrant) {
    if (registrant) {
        free(registrant);
    }
}

void internalNotifyRegistrant (Registrant* registrant, void* result, int resultSize, int errorCode) {
    Message* msg;

    if (!registrant || !registrant->handler) {
        return;
    }

    msg = messageObtain(registrant->handler, registrant->what, NULL);
    if (!msg) {
        return;
    }

    msg->obj = (void*)newAsyncResult(registrant->userObj, result, resultSize, errorCode);
    if (!msg->obj) {
        messageRecycleUnchecked(msg);
        return;
    }

    messageSendToTarget(msg);
}

void notifyAsyncResult(Registrant* registrant, AsyncResult* ar) {
    if (ar) {
        internalNotifyRegistrant (registrant, ar->result, ar->resultSize, ar->errorCode);
    } else {
        internalNotifyRegistrant (registrant, NULL, 0, 0);
    }
}

void notifyRegistrant(Registrant* registrant, void* result, int resultSize, int error) {
    internalNotifyRegistrant (registrant, result, resultSize, error);
}


